package gof.com.yew.singleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

import org.junit.Test;

public class SingletonLeakTest {
	
	//防止反射漏洞测试
	@Test
	public void testReflect() throws Exception {
		SingletonDemo06 s1 = SingletonDemo06.getInstance();
		SingletonDemo06 s2 = SingletonDemo06.getInstance();
		System.out.println(s1);
		System.out.println(s2);

		@SuppressWarnings("unchecked")
		Class<SingletonDemo06> clazz = (Class<SingletonDemo06>)Class.forName("gof.com.yew.singleton.SingletonDemo06");
		Constructor<SingletonDemo06> c = clazz.getDeclaredConstructor();
		c.setAccessible(true);
		SingletonDemo06 s3 = (SingletonDemo06)c.newInstance();
		System.out.println(s3);
	}
	
	//防止反序列化漏洞测试
		@Test
		public void testSerializablet() throws Exception {
			SingletonDemo07 s1 = SingletonDemo07.getInstance();
			SingletonDemo07 s2 = SingletonDemo07.getInstance();
			System.out.println(s1);
			System.out.println(s2);

			//写入文件
			FileOutputStream fos = new FileOutputStream("F:\\a.txt");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(s1);
			oos.close();
			fos.close();
			
			//反序列化生成对象
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\a.txt"));
			SingletonDemo07 s3 = (SingletonDemo07) ois.readObject();
			ois.close();
			System.out.println(s3);
		}
	
}
